package com.espirit.eap.manager;

import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.googlecode.cswish.struts.spring.CacheService;
import com.googlecode.cswish.struts.spring.GenericService;
import com.googlecode.cswish.util.OgnlExUtil;

@Service
public class SystemDataService {

	@Resource
    private GenericService genericService;
	
	@Resource
	private CacheService cacheService;
	
	@Resource
	private OgnlExUtil ognlExUtil;
	
	private Map<String, String> cache;
	
	private final static String NULL = new String();
	
	@PostConstruct
	private void init() {
		cache = cacheService.newCache(String.class, 10000);
	}
	
	public <T> T getValue(String key, boolean enableCache, T defaultValue) {
		String value = null;
		if (enableCache) {
			value = cache.get(key);
		}
		if (value == null) {
			value = getValue(key);
			
			if (value == null) {
				value = NULL;
			}
			cache.put(key, value);
		}
		
		if (value == NULL) {
			value = null;
		}
		
		T ret;
		if (value == null) {
			ret = defaultValue;
		} else {
			if (defaultValue == null || defaultValue instanceof String) {
				ret = (T)value;
			} else {
				Class<T> clazz = (Class<T>)defaultValue.getClass();
				ret = ognlExUtil.convertValue(value, clazz);
			}
		}
		return ret;
	}
	
	public String getValue(String key) {
		SystemData systemData = new SystemData();
		systemData.setDataKey(key);
		SystemData dbSystemData = genericService.searchAll(systemData).getData(0);
		if (dbSystemData != null) {
			return dbSystemData.getDataValue();
		} else {
			return null;
		}
	}
	
	public void setValue(String key, String value) {
		SystemData systemData = new SystemData();
		systemData.setDataKey(key);
		SystemData dbSystemData = genericService.searchAll(systemData).getData(0);
		if (dbSystemData == null) {
			// add new record
			systemData.setDataValue(value);
			dbSystemData = genericService.merge(systemData);
		} else {
			// update the existed record
			if (!StringUtils.equals(dbSystemData.getDataValue(), value)) {
				dbSystemData.setDataValue(value);
				dbSystemData = genericService.merge(dbSystemData);
			}
		}
		
		// update the cache
		if (cache.containsKey(key)) {
			cache.put(key, value);
		}
	}
}